<?php
$this_dir = dirname(__FILE__) . '/';
require_once($this_dir . '../plugin/autoload.php');
$tmp = parse_url($_SERVER['REQUEST_URI']);
$uri = $tmp['path']; //因为REQUEST_URI带get参数，影响路由。

$rules = ConfLib::get('route', 'controller');
$controller_name = '';

function route($rules, $uri) {
    foreach($rules as $k=>$v) {
        if(1 === preg_match('/' . $k . '/', $uri)) {
            return $v;
        }
    }
    throw new Exception();
}

$controller_name = route($rules, $uri);

$c = new $controller_name ($uri);
$r = $c->route();
function getStatusStr($code) {
    //fastcgi与apache module不同
    //这里按照fastcgi格式
    //http://cn.php.net/manual/en/function.header.php
    $http_code_map = array(
        '200' => '200 OK',
        '301' => 'Moved Permanently',
        '302' => 'Found',
        '404' => '404 Not Found',
    );
    return 'Status: ' . $http_code_map[$code];
}
function output($r) {
    //fastcgi与apache module不同
    //这里按照fastcgi格式
    //http://cn.php.net/manual/en/function.header.php
    if(in_array($r['http']['status_code'], array(302, 301))) {
        header('Location: ' . $r['http']['uri']); //todo header status code
        exit;
    } else {
        header(getStatusStr($r['http']['status_code']));
    }
    $v = $r['data'];
    header('Content-Type: ' . $r['http']['content-type']);
    switch($r['http']['content-type']) {
        case 'text/html' :
            $v['static_uri'] = ConfLib::get('static', 'uri');
            require dirname(__FILE__) . '/../view/default/'. $r['tpl'] . '.tpl';
            break;
        case 'text/plain' :
            echo $v;
            break;
        case 'application/json' :
            echo json_encode($v);
            break;
        case 'application/atom+xml' :
            //todo
            break;
    }
    return true;
}
output($r);
exit;
?>
